package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.Company;
import com.cdgeekcamp.redas.db.model.CompanyRepository;
import com.cdgeekcamp.redas.lib.core.api.receivedParameter.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class CompanyBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private CompanyRepository companys;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        String mainPage = recrPage.getCompanyMainPage();
        String companyName = recrPage.getCompanyName();
        String companyScale = recrPage.getScale();
        Integer companyScaleLeft = recrPage.getScaleLeft();
        Integer companyScaleRight = recrPage.getScaleRight();

        Optional<Company> companyOpt = companys.findByName(companyName);
        Company company;

        if (companyOpt.isEmpty()) {
            log.info(String.format("公司：%s 不存在，新建中......", companyName));
            company = companys.save(new Company(mainPage, companyName, companyScale, companyScaleLeft, companyScaleRight));
        } else {
            company = companyOpt.get();
            log.info(String.format("公司：%s 存在，更新中......", companyName));
            company.setMainPage(mainPage);
            company.setName(companyName);
            company.setScale(companyScale);
            company.setScaleLeft(companyScaleLeft);
            company.setScaleRight(companyScaleRight);
            companys.save(company);
        }

        return company.getId();
    }
}
